package m.jclecai.com.view;

import android.content.Context;
import android.graphics.Color;
import android.graphics.Rect;
import android.text.Html;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.util.Log;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.AlphaAnimation;
import android.view.animation.OvershootInterpolator;
import android.view.animation.TranslateAnimation;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TextView;

import com.facebook.rebound.Spring;
import com.facebook.rebound.SpringConfig;
import com.facebook.rebound.SpringSystem;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import m.jclecai.com.R;
import m.jclecai.com.animal.ExpandAnimation;
import m.jclecai.com.bean.HomeItem;
import m.jclecai.com.listener.Callback;
import m.jclecai.com.listener.MySpringListener;
import m.jclecai.com.utils.ScreenUtil;

/**
 * Created by ZD on 2017/6/24.
 */

public class ExGridView extends ScrollView {

    LinearLayout parent;
    //记录是否点击的view
    View clickView;
    List<HomeItem> menu;
    int mDuration = 500;

    public ExGridView(Context context) {
        super(context);
    }

    public ExGridView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public ExGridView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    public void setMenu(List<HomeItem> menu) {
        //this.menu = filterData(menu);
        this.menu=menu;
        clickView = null;
        parent = null;
        init();
    }

    List<HomeItem> filterData(List<HomeItem> menu) {
        Iterator<HomeItem> iterator = menu.iterator();
        if (menu != null)
            while (iterator.hasNext()) {
                if (iterator.next().getStatus().equals("1"))
                    iterator.remove();
            }
        return menu;
    }

    void init() {
        if (menu == null) return;
        if (menu.size() % 2 != 0) {
            menu.add(new HomeItem());
        }
        removeAllViews();
        parent = new LinearLayout(getContext());
        //排放方式
        parent.setOrientation(LinearLayout.VERTICAL);
        addView(parent);
        //
        LinearLayout son = null;
        for (int i = 0; i < menu.size(); i++) {
            HomeItem homeItem = menu.get(i);
            if (i == 0 || i % 2 == 0) {
                son = new LinearLayout(getContext());
                LinearLayout hide = new LinearLayout(getContext());
                parent.addView(son);
                parent.addView(hide);
                addHideView(hide, i);
            }
            son.setOrientation(LinearLayout.HORIZONTAL);
            addMainView(son, i, R.color.font_white, homeItem, true);
        }
        callback.callbackSuccess();
        // addFooter();         ///这里我们的业务逻辑稍微发生了点变化，就是这里的微信公众号，是需要从网络获取的；如果没有就不显示
    }

    //添加主体
    void addMainView(LinearLayout s, final int i, int bgColor, final HomeItem homeItem, final boolean close) {
        View inflate = View.inflate(getContext(), R.layout.home_adapter_item, null);        //一个条目
        s.addView(inflate);
        LinearLayout.LayoutParams lp = (LinearLayout.LayoutParams) inflate.getLayoutParams();
        lp.width = 0;
        lp.weight = 1;
        ImageView img = (ImageView) inflate.findViewById(R.id.iv_icon);     //彩种图标；
        TextView name = (TextView) inflate.findViewById(R.id.tv_name);      //一级标题
        TextView deplct = (TextView) inflate.findViewById(R.id.tv_deplct);  //二级标题
        img.setImageResource(homeItem.getIcon());
        for (HomeItem item : menus) {
            if (TextUtils.isEmpty(homeItem.getType())) break;
            if (item.getTypes().equals(homeItem.getLogo())) {
                img.setImageResource(item.getIcon());
                break;
            }
        }
        name.setText(homeItem.getType());
        deplct.setText(homeItem.getTitle());
        inflate.setBackgroundResource(bgColor);     //设置背景颜色；
        inflate.findViewById(R.id.ll_body).setBackgroundResource(bgColor);
        inflate.setTag(homeItem);           //将条目的View，通过tag的形式设置进去
        //过滤创建的虚拟数据
        if (TextUtils.isEmpty(homeItem.getTitle())
                && TextUtils.isEmpty(homeItem.getType()) ) {
            return;
        }
        inflate.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!close) {
                    onItemClick(homeItem);
                    return;
                }
                //当前所点击view的父容器所在整个容器的下标
                int index = parent.indexOfChild((View) v.getParent());  //item的容器
                View hide = parent.getChildAt(index + 1);               //隐藏的view
                boolean b = clickView != null && clickView == v;
                changeHideViewData(hide, homeItem, i, b);
                int animationDuration = getAnimationDuration(homeItem);
                if (clickView == null) {
                    if (homeItem.getItem() != null && homeItem.getItem().size() > 0) {
                        startAnimation(hide, animationDuration);
                    }
                } else {
                    View vp = (View) clickView.getParent();
                    int cIndex = parent.indexOfChild(vp);
                    if (homeItem.getItem() != null && homeItem.getItem().size() > 0) {
                        if (index == cIndex) {
                            if (clickView.equals(v) || hide.getVisibility() == GONE) {
                                animationDuration = 0;
                                //如果点击的是同一列的同个view 则展开项 隐藏显示
                                startAnimation(hide, animationDuration);
                            }
                        } else {
                            if (homeItem.getItem() != null && homeItem.getItem().size() > 0)
                                animationDuration = 0;
                            View mainView = parent.getChildAt(cIndex + 1);
                            if (mainView.getVisibility() == VISIBLE)
                                //如果是不同列或者点击了没有子项的则移除
                                startAnimation(mainView, animationDuration);
                            startAnimation(hide, animationDuration);
                        }
                    } else {
                        View mainView = parent.getChildAt(cIndex + 1);
                        Log.e("view", mainView.toString());
                        if (mainView.getVisibility() == VISIBLE)
                            //如果是不同列或者点击了没有子项的则移除
                            startAnimation(mainView, animationDuration);
                    }
                }
                if (homeItem.getItem() != null)
                    arrawMove(hide, v);
                clickView = v;
            }
        });
    }

    //移动箭头
    void arrawMove(View hide, View click) {
        Rect or = new Rect();
        if (clickView != null)
            clickView.getGlobalVisibleRect(or);
        Rect nr = new Rect();
        click.getGlobalVisibleRect(nr);
        final View viewById = hide.findViewById(R.id.iv_arraw);
        if (viewById == null) return;
        if (viewById.getTranslationX() >= nr.left + nr.width() / 2 + 1 && nr.left > 0
                || viewById.getTranslationX() == nr.left + nr.width() / 2 + 1)
            return;
        Spring spring = SpringSystem.create().createSpring();
        spring.setCurrentValue(or.left + nr.width() / 2);
        spring.setEndValue(nr.left + nr.width() / 2 + 1);
        spring.setSpringConfig(SpringConfig.fromOrigamiTensionAndFriction(200, 12));
        spring.addListener(new MySpringListener() {
            @Override
            public void onSpringUpdate(Spring spring) {
                double currentValue = spring.getCurrentValue();
                viewById.setTranslationX((int) currentValue);
            }
        });
    }

    //添加隐藏的girdview
    void addHideView(LinearLayout h, int i) {
        View inflate = View.inflate(getContext(), R.layout.home_adapter_item, null);
        h.addView(inflate);
        h.setVisibility(GONE);
        inflate.findViewById(R.id.iv_arraw).setVisibility(VISIBLE);
        LinearLayout.LayoutParams lp = (LinearLayout.LayoutParams) inflate.getLayoutParams();
        lp.weight = 1;
        ViewGroup vg = (ViewGroup) inflate.findViewById(R.id.ll_body);
        vg.setBackgroundResource(R.color.color_dddddd);
    }

    //更新值
    void changeHideViewData(View hide, HomeItem homeItem, int index, boolean b) {
        hide.findViewById(R.id.iv_arraw).setVisibility(VISIBLE);
        LinearLayout vg = (LinearLayout) hide.findViewById(R.id.ll_body);
        vg.setBackgroundResource(R.color.color_dddddd);
        List<HomeItem> items = homeItem.getItem();
        LinearLayout vp = (LinearLayout) vg.getChildAt(0);
        vp.setOrientation(LinearLayout.VERTICAL);
        vp.setGravity(Gravity.NO_GRAVITY);
        if (items != null) {
            vp.removeAllViews();
            LinearLayout son = null;
            for (int i = 0; i < items.size(); i++) {
                if (i == 0 || i % 2 == 0) {
                    son = new LinearLayout(getContext());
                    son.setBackgroundResource(R.color.color_dddddd);
                    vp.addView(son);
                }
                son.setOrientation(LinearLayout.HORIZONTAL);
                addMainView(son, i, R.color.color_dddddd, items.get(i), false);
            }
            if (!b) {
                if ((index + 1) % 2 != 0)
                    getTransAlaphAnimation(vp, getResources().getDisplayMetrics().widthPixels, 0);
                else
                    getTransAlaphAnimation(vp, -getResources().getDisplayMetrics().widthPixels, 0);
            }
        } else {
            vp.startAnimation(getAlphaAnimation(1, 0));
            onItemClick(homeItem);
        }
    }

    void startAnimation(final View view, final int duration) {
        postDelayed(new Runnable() {
            @Override
            public void run() {
                view.startAnimation(new ExpandAnimation(view, mDuration, view.getVisibility() != VISIBLE));
            }
        }, duration);
    }

    int getAnimationDuration(HomeItem homeItem) {
        int duration;
        if (clickView != null) {
            HomeItem ht = (HomeItem) clickView.getTag();
            if (homeItem.getTitle().equals(ht.getTitle())
                    || ht.getTitle().equals(homeItem.getParent())) {
                //点击的同一个view
                duration = 0;
            } else {
                if (ht.getItem() != null)
                    duration = this.mDuration;
                else
                    duration = 0;
            }
        } else {
            duration = 0;
        }
        return duration;
    }

    void onItemClick(final HomeItem homeItem) {
        //先收缩展开的view 在跳转activity
//        int duration = getAnimationDuration(homeItem);
//        postDelayed(new Runnable() {
//            @Override
//            public void run() {
        if (callback != null)
            callback.onItemClick(homeItem);
//            }
//        }, duration);
    }

    void getTransAlaphAnimation(final View v, float from, float to) {
        TranslateAnimation animation = new TranslateAnimation(from, to, 0, 0);
        animation.setInterpolator(new OvershootInterpolator() {
            @Override
            public float getInterpolation(float input) {
                float v1 = Math.abs(input) + 0.3f;
                v1 = v1 > 1 ? 1 : v1;
                v.setAlpha(v1);
                return super.getInterpolation(input);
            }
        });
        animation.setDuration(mDuration);
        v.startAnimation(animation);
    }

    AlphaAnimation getAlphaAnimation(int from, int to) {
        AlphaAnimation animation = new AlphaAnimation(from, to);
        animation.setDuration(mDuration);
        return animation;
    }

    public void addFooter(){
        addFooter(getResources().getString(R.string.home));
    }

    //添加脚
    public void addFooter(String weChat) {
        TextView tv = new TextView(getContext());
        tv.setBackgroundColor(Color.rgb(244, 244, 244));
        tv.setGravity(Gravity.CENTER);
        parent.addView(tv);
        tv.setTextSize(TypedValue.COMPLEX_UNIT_SP, 13);
        //tv.setText(Html.fromHtml(getResources().getString(R.string.home)));
        tv.setText(Html.fromHtml(weChat));
        LinearLayout.LayoutParams lp = (LinearLayout.LayoutParams) tv.getLayoutParams();
        lp.height = ScreenUtil.dip2px(getContext(), 50);
        tv.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                if (callback != null)
                    callback.onClickSetChangedText();
            }
        });
    }

    public Callback callback;

    public void setCallback(Callback callback) {
        this.callback = callback;
    }

    List<HomeItem> menus = new ArrayList<HomeItem>() {{
        add(new HomeItem("竞彩足球", R.drawable.types_jczq, "德国vs英格兰", "jczq"));
        add(new HomeItem("胜负彩", R.drawable.sfclogo, "竞猜14场比赛", "sfc"));
        add(new HomeItem("竞彩篮球", R.drawable.jclqlogo, "骑士vs掘金", "jclq"));
        add(new HomeItem("任九场", R.drawable.r9logo, "竞猜9场比赛", "rxj"));
        add(new HomeItem("任九场", R.drawable.r9logo, "竞猜9场比赛", "rjc"));

        add(new HomeItem("世界杯冠军", R.mipmap.cuplogo, "", "jcgj"));

    }};
}
